<template>
  <!-- 会员编辑-送优惠券 -->
  <div>
    <el-dialog
      v-model="visible"
      :title="$t('user.selectCoupons')"
      width="60%"
      class="select-coupon-dialog"
    >
      <el-form
        :inline="true"
        :model="searchForm"
        class="demo-form-inline form"
      >
        <el-form-item>
          <el-input
            v-model="couponName"
            :placeholder="$t('user.couponTip1')"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <div
            class="default-btn primary-btn"
            @click="onSearch"
          >
            {{ $t("pictureManager.query") }}
          </div>
        </el-form-item>
      </el-form>
      <div class="main-container">
        <div class="prods-select-body table-con">
          <el-table
            ref="couponTableRef"
            v-loading="dataListLoading"
            :data="dataList"
            header-cell-class-name="table-header"
            row-class-name="table-row-low"
            style="width: 100%;"
            @selection-change="selectChangeHandle"
          >
            <el-table-column
              v-if="isSingle"
              width="50"
            >
              <template #default="scope">
                <div>
                  <!-- native modifier has been removed, please confirm whether the function has been affected  -->
                  <el-radio
                    v-model="singleSelectCouponId"
                    :label="scope.row.couponId"
                    @change="getSelectProdRow(scope.row)"
                  >
                    &nbsp;
                  </el-radio>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              v-if="!isSingle"
              type="selection"
              width="50"
            />
            <el-table-column
              prop="couponName"
              :label="$t('marketing.couponName')"
              width="200"
            >
              <template #default="scope">
                <span class="table-cell-text"> {{ scope.row.couponName }} </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="couponType"
              :label="$t('coupon.couponType')"
            />
            <el-table-column
              prop="stocks"
              :label="$t('user.stockNum')"
            />
            <el-table-column
              prop="limitNum"
              :label="$t('user.couponUpperLimit')"
            />
            <el-table-column
              align="center"
              :label="$t('user.perRecevies')"
              width="160"
            >
              <template #header>
                <span>{{ $t('user.perRecevies') }}</span>
                <el-popover
                  placement="top"
                  width="200"
                  trigger="hover"
                  :content="$t('user.couponTip2')"
                >
                  <template #reference>
                    <el-icon><QuestionFilled /></el-icon>
                  </template>
                </el-popover>
              </template>
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.eachObtain"
                  size="small"
                  controls-position="right"
                  :min="scope.row.stocks>0?1:0"
                  :max=" scope.row.stocks>0?(scope.row.stocks >= scope.row.limitNum ? scope.row.limitNum:scope.row.stocks):0"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination
          v-if="dataList.length"
          :current-page="page.pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="page.pageSize"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
        />
      </div>
      <el-alert
        :title="$t('user.sendCouponTips')"
        type="warning"
        show-icon
        :closable="false"
      />
      <template #footer>
        <div>
          <div
            class="default-btn"
            @click="visible = false"
          >
            {{ $t('user.cancel') }}
          </div>
          <div
            class="default-btn primary-btn"
            @click="submitProds()"
          >
            {{ $t('user.confirm') }}
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Debounce } from '@/utils/debounce.js'
import { ElMessage } from 'element-plus'

const props = defineProps({
  value: {
    default: '',
    type: String
  },
  // 获取方式 null:默认（客户领取+平台发放） 0=客户领取 1=平台发放
  getWay: {
    default: null,
    type: Number
  },
  isSingle: {
    default: false,
    type: Boolean
  },
  // 最大上传数量
  limit: {
    default: 9,
    type: Number
  }
})

const emit = defineEmits(['refreshSelectCouponList', 'refreshDataList'])

const dataForm = reactive({
  userIds: [],
  coupons: []
})

const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})

const visible = ref(false)
const init = (ids) => {
  visible.value = true
  dataForm.userIds = ids
  getDataList()
}
// 每页数
const sizeChangeHandle = (val) => {
  page.pageSize = val
  page.currentPage = 1
  getDataList(page)
}
// 当前页
const currentChangeHandle = (val) => {
  page.currentPage = val
  getDataList(page)
}

const dataListLoading = ref(false)
const dataList = ref([]) // 标签
const searchForm = ref({})
// 分页获取标签
const getDataList = (pageParam) => {
  dataListLoading.value = true
  http({
    url: http.adornUrl('/admin/coupon/listCanSendCoupon'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.pageSize : pageParam.pageSize,
          getWay: props.getWay
        },
        searchForm.value
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    dataList.value.forEach(item => {
      // 平台投放 / 用户领取
      item.couponType = item.couponType === 1 ? $t('product.voucher') : (item.couponType === 2 ? $t('coupon.discountVoucher') : (item.couponType === 3 ? $t('user.coinCertificate') : ''))
      item.eachObtain = 1
    })
    page.total = data.total
    dataListLoading.value = false
  })
}

const couponName = ref(null)
// 搜索
const onSearch = () => {
  searchForm.value.couponName = couponName.value
  getDataList(page)
}

let dataListSelections = []
// 单选商品事件
const getSelectProdRow = (row) => {
  dataListSelections = [row]
}

// 多选
// 多选点击事件
const selectChangeHandle = (selection) => {
  dataList.value.forEach((tableItem) => {
    const selectedProdIndex = selection.findIndex((selectedCoupon) => {
      if (!selectedCoupon) {
        dataListSelections = []
        return false
      }
      return selectedCoupon.couponId === tableItem.couponId
    })
    const dataSelectedProdIndex = dataListSelections.findIndex((dataSelectedCoupon) => dataSelectedCoupon.couponId === tableItem.couponId)
    if (selectedProdIndex > -1 && dataSelectedProdIndex === -1) {
      dataListSelections.push(tableItem)
    } else if (selectedProdIndex === -1 && dataSelectedProdIndex > -1) {
      dataListSelections.splice(dataSelectedProdIndex, 1)
    }
  })
}

// 确定事件
const submitProds = () => {
  // 商品单选的情况
  if (props.isSingle) {
    dataListSelections.length && emit('refreshSelectCouponList', dataListSelections[0])
    dataListSelections = []
    visible.value = false
    return
  }
  // 多选
  const coupons = []
  if (dataListSelections.length >= 1) {
    dataListSelections.forEach(item => {
      const couponIndex = coupons.findIndex((coupon) => coupon.couponId === item.couponId)
      if (couponIndex === -1) {
        coupons.push({ couponId: item.couponId, couponName: item.couponName, subTitle: item.subTitle, limitNum: item.limitNum, eachObtain: item.eachObtain })
      }
    })
  }
  dataForm.coupons = coupons
  dataListSelections = []
  confirm()
}

const confirm = Debounce(() => {
  if (!dataForm.userIds) {
    return
  }
  if (!dataForm.coupons || !dataForm.coupons.length) {
    return ElMessage.error($t('coupon.pleaseSelectCoupon'))
  }
  const coupons = []
  dataForm.coupons.forEach(element => {
    const obj = {}
    obj.couponId = element.couponId
    obj.nums = element.eachObtain
    coupons.push(obj)
  })
  dataForm.coupons = coupons
  http({
    url: http.adornUrl('/admin/coupon/sendUserCoupon'),
    method: 'put',
    data: http.adornData(dataForm)
  }).then(() => {
    ElMessage({
      message: $t('user.success'),
      type: 'success',
      duration: 1500,
      onClose: () => {
        visible.value = false
        emit('refreshDataList', page)
      }
    })
  }).catch(() => {})
}, 1000)

defineExpose({
  init
})

</script>
<style lang="scss" scoped>
@use "index";
</style>
